# -*- coding:utf-8 -*-
# @Time: 2020/8/7 10:54
# @Author: liupengfei
# @File: filters.py

import django_filters
from django.contrib.contenttypes.models import ContentType

from .models import Comment


class CommentFilter(django_filters.FilterSet):
    model_name = django_filters.CharFilter(method='filter_model_name')
    object_id = django_filters.CharFilter(method='filter_object_id')
    parent = django_filters.CharFilter(field_name='parent')

    def filter_model_name(self, queryset, *args):
        model_name = args[1]
        if model_name:
            content_type = ContentType.objects.get(model=model_name.lower())
            queryset = queryset.filter(content_type=content_type)
        return queryset

    def filter_object_id(self, queryset, *args):
        object_id = args[1]
        if object_id:
            queryset = queryset.filter(object_id=object_id)
        return queryset

    class Meta:
        model = Comment
        fields = '__all__'
